package durst.action.account.include;

import java.sql.SQLException;
import java.util.List;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;

import com.sdicons.json.mapper.MapperException;

import durst.action.CalendarBasicAction;
import durst.data.Account;
import durst.data.Friend;
import durst.data.dao.DaoFactory;
import durst.data.dao.impl.FriendDao;

@UrlBinding("/action/auto/{query}")
public class AutocompleteFriendAction extends CalendarBasicAction {
	private String query;

	@SuppressWarnings("unchecked")
	@DefaultHandler
	public Resolution autocomplete() throws SQLException, MapperException {
		FriendDao<Friend, Integer> dao = (FriendDao<Friend, Integer>)DaoFactory.getInstance().createDao(Friend.class);

		List<Account> suggestions;
		try {
			suggestions = dao.findFriends(context.getAccount(), Integer.parseInt(query), query, query);
		} catch (NumberFormatException err) {
			suggestions = dao.findFriends(context.getAccount(), null, query, query);
		}
		
		context.getRequest().setAttribute("suggestions", suggestions);

		return new ForwardResolution("/account/includes/suggestions.jsp");
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public String getQuery() {
		return query;
	}
}
